import { ElNotification } from "element-plus"
import { getAxios } from "/axios"
let modules = import.meta.glob("../views/**/*.vue")
function addRouter(routerList, router) {
	routerList.forEach(route => {
		if (!route.viewPath) return
		router.addRoute("Home", {
			path: route.viewPath,
			meta: {
				title: route.name || route.remark || route.id,
				id: route.id,
				remark: route.remark,
				icon: route.icon || "",
				close_leave: route.type != 1,
			},
			name: route.viewPath || route.name || route.id + "",
			component: modules["../views" + route.viewPath + ".vue"],
		})
	})
}
export async function createRouterList(router) {
	if (!window.localStorage.getItem("token")) return
	try {
		const oldRouterList = JSON.parse(window.localStorage.getItem("routerList") || "[]")
		addRouter(oldRouterList, router)
		const newRouterList = await getAxios("/system/menu/routers")
		window.localStorage.setItem("routerList", JSON.stringify(newRouterList))
		const newRouterIds = newRouterList.map(item => item.id)
		oldRouterList.forEach(route => {
			if (!newRouterIds.includes(route.id)) {
				router.removeRoute(route.viewPath)
			}
		})
		addRouter(newRouterList, router)
	} catch (error) {
		console.error("获取路由出错: ", error)
		if (typeof error === "string") {
			ElNotification({ message: error, type: "error" })
		}
	}
}
